//
//  PersonalViewController.swift
//  HinsLive
//
//  Created by haoxian on 2019/4/19.
//  Copyright © 2019 Hins. All rights reserved.
//

import UIKit
import RxSwift
import RxCocoa
import Toast
import SVProgressHUD

class PersonalViewController: ViewController {
    
    private lazy var headerView: PersonalHeaderView = {
        let view = PersonalHeaderView(frame: .zero)
        _ = view.avatarSubject
            .flatMap(avatarDidTap)
            .subscribe(onNext: { (user) in
                AccountManager.share.changeUserInfo(user)
            }, onError: { [weak self] (error) in
                self?.view.makeCenterMsg(error.localizedDescription)
            })
        return view
    }()
    
    private lazy var tableView: UITableView = {
        let tableView = UITableView(frame: .zero, style: .grouped)
        tableView.dataSource = self
        tableView.delegate = self
        tableView.isScrollEnabled = false
        tableView.bounces = false
        tableView.register(UITableViewCell.self, forCellReuseIdentifier: "\(UITableViewCell.self)")
        
        return tableView
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupUI()
        NotificationCenter.default.rx
            .notification(.userStateDidChange)
            .observeOn(MainScheduler.asyncInstance)
            .subscribe(onNext: { [weak self] _ in
                self?.headerView.updateUserInfo()
                self?.tableView.reloadData()
            })
            .disposed(by: bag)
    }
}

private extension PersonalViewController {
    func setupUI() {
        view.backgroundColor = .white
        view.addSubview(headerView)
        headerView.snp.makeConstraints { (make) in
            make.top.left.right.equalToSuperview()
            make.height.equalTo(274)
        }
        view.addSubview(tableView)
        tableView.snp.makeConstraints { (make) in
            make.top.lessThanOrEqualTo(headerView.snp.bottom)
            make.left.right.equalToSuperview()
            make.bottom.equalTo(view.safeAreaLayoutGuide.snp.bottom)
        }
    }
    
    var avatarDidTap: () -> Observable<Event<UserInfo>> {
        let o = UIImagePickerController.rx.create(self) { (imagePicker) in
                imagePicker.sourceType = .photoLibrary
                imagePicker.allowsEditing = true
            }
            .flatMap { $0.rx.didFinishPickingMediaWithInfo }
            .take(1)
            .map { info -> Data? in
                let image = info[.editedImage] as? UIImage
                return image?.thumbnailImageData()
            }
            .unwrap()
            .map { data -> UserAvatarChangeRequest in
                return UserAvatarChangeRequest.with {
                    $0.uid = AccountManager.share.user.uid
                    $0.imageData = data
                }
            }
            .flatMapLatest(Network.userAvatarChange)
        return { o }
    }
    
    func changeName(_ name: String) {
        _ = Network.userNameChange(UserNameChangeRequest.with({
                $0.uid = AccountManager.share.user.uid
                $0.name = name
            }))
            .subscribe(onNext: { (user) in
                AccountManager.share.changeUserInfo(user)
            }, onError: { [weak self] error in
                self?.view.makeCenterMsg(error.localizedDescription)
            })
    }
}

extension PersonalViewController: UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int {
        return 2
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if section == 0 {
            return AccountManager.share.isLogin ? 2 : 1
        } else {
            return 1
        }
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "\(UITableViewCell.self)", for: indexPath)
        if indexPath.section == 0 {
            cell.accessoryType = .disclosureIndicator
            cell.textLabel?.font = .systemFont(ofSize: 16)
            cell.textLabel?.textColor = .black
            cell.textLabel?.textAlignment = .left
            if indexPath.row == 0 {
                cell.textLabel?.text = "缓存"
            } else if indexPath.row == 1 {
                cell.textLabel?.text = "编辑个人信息"
            }
        } else if indexPath.section == 1 {
            if indexPath.row == 0 {
                cell.accessoryType = .none
                cell.textLabel?.font = UIFont.systemFont(ofSize: 18)
                cell.textLabel?.textColor = AccountManager.share.isLogin ? .red : .standardColor 
                cell.textLabel?.textAlignment = .center
                cell.textLabel?.text = AccountManager.share.isLogin ? "退出登录" : "登录"
            }
        }
        return cell
    }
}

extension PersonalViewController: UITableViewDelegate {
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if indexPath.section == 0 {
            if indexPath.row == 1 {
                let editVc = UserInfoEditViewController(nib: R.nib.userInfoEditViewController)
                _ = editVc.doneSubject.subscribe(onNext: { [weak editVc, weak self] (name) in
                    editVc?.safeDismiss()
                    self?.changeName(name)
                })
                present(editVc, animated: true)
            }
        } else if indexPath.section == 1 {
            if indexPath.row == 0 {
                let loginVc = LoginViewController(nib: R.nib.loginViewController)
                let nav = UINavigationController(rootViewController: loginVc)
                nav.isNavigationBarHidden = true
                present(nav, animated: true, completion: {
                    AccountManager.share.logout()
                })
            }
        }
        tableView.cellForRow(at: indexPath)?.isSelected = false        
    }
}
